package com.xuecheng.checkcode.factory;

import com.xuecheng.checkcode.enums.CheckCodeType;
import com.xuecheng.checkcode.service.CheckCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: 验证码服务工厂
 * @date 2025/4/7 17:19
 */
@Component
public class CheckCodeServiceFactory {

    /**
     * 策略映射表
     */
    private final Map<String, CheckCodeService> strategyMap;

    /**
     * 构造函数，注入所有类型的策略，体现了工厂容器的初始化，这里实际拿的更底层的spring工厂中的实例
     * @param picService 图片验证码生成策略
     * @param smsService 短信验证码生成策略
     * @param emailService 邮箱验证码生成策略
     */
    @Autowired
    public CheckCodeServiceFactory(
            @Qualifier("PicCheckCodeService") CheckCodeService picService,
            @Qualifier("SmsCheckCodeService") CheckCodeService smsService,
            @Qualifier("EmailCheckCodeService") CheckCodeService emailService
    ) {
        strategyMap = new HashMap<>();
        strategyMap.put(CheckCodeType.PIC.getValue(), picService);
        strategyMap.put(CheckCodeType.SMS.getValue(), smsService);
        strategyMap.put(CheckCodeType.EMAIL.getValue(), emailService);
    }

    /**
     * 根据类型获取对应的策略，模拟创建指定的产品
     * @param type 类型
     * @return 策略
     */
    public CheckCodeService getCheckCodeService(CheckCodeType type) {
        CheckCodeService strategy = strategyMap.get(type.getValue());
        if (strategy == null) {
            throw new IllegalArgumentException("Unsupported checkcode type: " + type);
        }
        return strategy;
    }
}
